<?php
/******************************************
 *   说明: 提供一些常用的与sql相关的函数
 * author: fenghao
 *   date: 2012-04-01
 *
 ******************************************/

class SqlFuncs{

    /**
     * 给定查询条件，生成相应的sql
     * @param array $condition_field 条件数组 array('cond1'=>'va1', 'cond2'=>'va2')
     * 当一个条件给定多个值是可以使用如下方式 array('user_id'=>array(id1,id2,....))
     */
    static public function getSqlCondition($condition_field){
        $sqlcmd = "";
        if(!empty($condition_field) && is_array($condition_field)){
            foreach($condition_field as $key => $value){
                if(!is_array($value)){
                    $sqlcmd .= " `$key` = '$value' AND ";
                }else{
                    $sqlcmd .= " `$key` in ('".implode("','", $value)."') AND ";
                }
            }
            $sqlcmd .= " 1 ";
        }else if(is_string($condition_field)){
            $sqlcmd .= $condition_field;
        }
        return $sqlcmd;
    }
    
    //给定查询的字段，生成相应的sql
    static public function getSqlQueryField($query_field){
        $sqlcmd = "";
        if(is_string($query_field)){
            $sqlcmd .= $query_field;
        }else if(!empty($query_field) && is_array($query_field)){
            foreach ($query_field as $key => $value){
                //判断是否有索引
                if(!is_numeric($key)){
                    $query_field[$key] = " `$key` as $value ";
                }else{
                    $query_field[$key] = " `$value` ";
                }
            }
            $sqlcmd .= implode(",",$query_field);
        }
        return $sqlcmd;
    }

    //给定排序字段，生成order
    static public function getSqlOrder($order_field){
        $order = "";
        if(is_string($order_field)){
            $order .= $order_field;
        }else if(!empty($order_field) && is_array($order_field)){
            foreach ($order_field as $key => $value){
                if(!is_numeric($key)){
                    $order_field[$key] = " `$key` $value ";
                }else{
                    $order_field[$key] = " `$value` ";
                }
            }
            $order .=  implode(",",$order_field);
        }
        return ($order?"ORDER BY $order":"");
    }

}

?>
